using System;
using System.Runtime.Serialization;

namespace Needle.Bus.Messages.Management
{
    
    [DataContract]
    public class ErrorMessage : ControlMessage
    {

        public static ErrorMessage Create(
            Bus bus, 
            DateTime timestamp, 
            string destinationAddress, 
            IMessage message, 
            Exception error)
        {

            return new ErrorMessage
            {
                Timestamp = timestamp,
                EngineId = bus.Engine.Id,
                /* check if the stage is set so we get the immediate sender,
                 * else, assume the return address holds the sender, 
                 * this may well be an invalid assumption. */
                SourceAddress = bus.Stage != null
                                ? bus.Stage.Id
                                : (message is IRequest
                                    ? ((IRequest)message).ReturnAddress
                                    : BusAddress.Unknown),
                DestinationAddress = destinationAddress,
                Message = message,
                CorrelationId = (message is ICorrelation) ? ((ICorrelation)message).IdForCorrelation : null,
                Error = error
            };
        }

        [DataMember]
        public DateTime Timestamp { get; set; }
        [DataMember]
        public string EngineId { get; set; }
        [DataMember]
        public string SourceAddress { get; set; }
        [DataMember]
        public string DestinationAddress { get; set; }
        [DataMember]
        public IMessage Message { get; set; }
        [DataMember]
        public Exception Error { get; set; }

    }
}
